import os
import sys

# 配置
MAX_USER = 10
INPUT_FILE = "account_in.txt"
OUTPUT_FILE = "account_out.txt"

# 全局变量
users = []          # 存储所有用户信息 [dict, dict, ...]
current_user = None # 当前登录用户 dict
current_pos = -1    # 当前用户在 users 中的索引


class Account:
    def __init__(self, user_id, username, password, money):
        self.id = int(user_id)
        self.username = username.strip()
        self.password = password.strip()
        self.money = float(money)

    def __str__(self):
        return f"{self.id};{self.username};{self.password};{self.money:.2f}"


def init():
    """从文件加载用户数据"""
    global users
    print(f"正在加载数据从文件 {INPUT_FILE} ...")
    if not os.path.exists(INPUT_FILE):
        print(f"错误：文件 {INPUT_FILE} 不存在！")
        sys.exit(1)

    with open(INPUT_FILE, 'r', encoding='utf-8') as f:
        lines = f.readlines()

    users = []
    for line in lines:
        line = line.strip()
        if not line:
            continue
        parts = [p.strip() for p in line.split(';')]
        if len(parts) == 4:
            try:
                user = Account(parts[0], parts[1], parts[2], parts[3])
                if len(users) < MAX_USER:
                    users.append(user)
            except Exception as e:
                print(f"解析用户数据失败: {line} -> {e}")
    print(f"成功加载 {len(users)} 个用户。\n")


def display_user(user):
    """显示单个用户信息"""
    print("当前用户信息")
    print("============")
    print(f"用户帐号: {user.id}")
    print(f"用户姓名: {user.username}")
    print(f"用户密码: {user.password}")
    print(f"账户余额: {user.money:.2f}")


def search_valid_user(user_id, password):
    """查找用户，返回索引，失败返回 -1"""
    for i, u in enumerate(users):
        if u.id == int(user_id) and u.password == password:
            return i
    return -1


def user_login():
    """用户登录，最多3次机会"""
    global current_user, current_pos
    print("输入账户编号:")
    try:
        user_id = int(input().strip())
    except:
        print("无效的账户编号！")
        return False

    for i in range(3):
        print("输入用户密码:")
        password = input().strip()
        pos = search_valid_user(user_id, password)
        if pos != -1:
            current_user = users[pos]
            current_pos = pos
            print(f"登录成功！欢迎 {current_user.username}\n")
            return True
        else:
            if i < 2:
                print("密码错误，还有 {} 次机会。".format(3 - i - 1))
            else:
                print("密码错误次数过多，退出。")
    return False


def sync_user():
    """将当前登录用户同步回 users 列表"""
    if current_user is not None and 0 <= current_pos < len(users):
        users[current_pos] = current_user


def clear_screen():
    """清屏"""
    os.system('cls' if os.name == 'nt' else 'clear')


def welcome():
    """显示主菜单"""
    clear_screen()
    print("欢迎使用ATM机")
    print("=============")
    print("1. 取款           2. 查询")
    print("3. 修改密码       4. 转账")
    print("5. 退出系统")
    print("=============")
    print("请注意账户安全\n")


def withdraw():
    """取款功能"""
    print(">> 1. 取款模块 <<")
    try:
        amount = float(input("输入取款金额: "))
        if amount <= 0:
            print("金额必须大于0！")
        elif amount > current_user.money:
            print("余额不足！")
        else:
            current_user.money -= amount
            print(f"请取出现金: {amount:.2f}")
            print(f"剩余余额: {current_user.money:.2f}")
    except:
        print("输入无效金额！")
    input("\n按回车键返回主菜单...")


def select_user():
    """查询用户信息"""
    print(">> 2. 查询模块 <<")
    display_user(current_user)
    input("\n按回车键返回主菜单...")


def update_password():
    """修改密码"""
    print(">> 3. 修改密码 <<")
    old_pass = input("输入原密码: ").strip()
    if old_pass != current_user.password:
        print("原密码错误！")
        input("\n按回车键返回主菜单...")
        return

    new_pass = input("输入新密码: ").strip()
    if not new_pass:
        print("密码不能为空！")
        input("\n按回车键返回主菜单...")
        return

    confirm_pass = input("再次输入新密码: ").strip()
    if new_pass != confirm_pass:
        print("两次输入不一致！")
    else:
        current_user.password = new_pass
        print("密码修改成功！")
    input("\n按回车键返回主菜单...")


def transfer():
    """转账功能"""
    print(">> 4. 转账模块 <<")
    try:
        target_id = int(input("输入对方账户编号: "))
    except:
        print("账户编号无效！")
        input("\n按回车键返回主菜单...")
        return

    # 查找目标账户（不能转给自己）
    target_user = None
    for u in users:
        if u.id == target_id and u.id != current_user.id:
            target_user = u
            break

    if not target_user:
        print("对方账户不存在或为当前账户！")
    else:
        try:
            amount = float(input("输入转账金额: "))
            if amount <= 0:
                print("金额必须大于0！")
            elif amount > current_user.money:
                print("余额不足！")
            else:
                current_user.money -= amount
                target_user.money += amount
                print(f"成功转账 {amount:.2f} 给 {target_user.username}")
                print(f"当前余额: {current_user.money:.2f}")
                sync_user()  # 同步当前用户
        except:
            print("输入金额无效！")
    input("\n按回车键返回主菜单...")


def exit_menu():
    """退出系统，保存数据"""
    print(">> 5. 退出模块 <<")
    save_info()
    print("数据已保存，正在退出...")
    input("按回车键退出...")
    clear_screen()
    sys.exit(0)


def save_info():
    """保存所有用户信息到文件"""
    print(f"正在保存数据到 {OUTPUT_FILE} ...")
    with open(OUTPUT_FILE, 'w', encoding='utf-8') as f:
        for user in users:
            f.write(str(user) + '\n')
    print("保存成功！")


def main_menu():
    """主菜单循环"""
    while True:
        welcome()
        choice = input("请选择功能 (1-5): ").strip()

        if choice == '1':
            withdraw()
        elif choice == '2':
            select_user()
        elif choice == '3':
            update_password()
        elif choice == '4':
            transfer()
        elif choice in ['5', 'q', 'x']:
            exit_menu()
        else:
            print("输入无效，请输入 1~5 之间的数字。")
            input("按回车键继续...")


def main():
    """程序主入口"""
    init()
    if user_login():
        main_menu()
    else:
        print("登录失败，程序退出。")


if __name__ == "__main__":
    main()
